from apps.common.base.dao import BaseDao
from apps.merchant.shop.serializers import *
from decimal import Decimal
from apps.common.extension.customException import *
from apps.system.user.dao import UserDao


class ShopDao(BaseDao):
    MODEL_CLASS = Shop
    SERI_CLASS = ShopBaseSerializer

    def create(self, data):
        try:
            # 兼容定位经纬度精度
            if data.get('latitude'):
                data['latitude'] = str(Decimal(data.get('latitude')).quantize(Decimal('0.000000000')))
            if data.get('longitude'):
                data['longitude'] = str(Decimal(data.get('longitude')).quantize(Decimal('0.000000000')))
            # 只允许添加一个直营店商户
            if data.get('types') == '0' and ShopDao().findAll().filter(types='0').exists():
                raise VerifyException('只能添加一个自营店')
            # 调用父类的 create 方法
            return super().create(data)
        except Exception as e:
            raise e
        
    def update(self, obj_id, data):
        try:
            # 兼容定位经纬度精度
            if data.get('latitude'):
                data['latitude'] = str(Decimal(data.get('latitude')).quantize(Decimal('0.000000000')))
            if data.get('longitude'):
                data['longitude'] = str(Decimal(data.get('longitude')).quantize(Decimal('0.000000000')))
            # 如果加盟店状态改为拒绝，把该加盟店下的商品全部下架，并且暂停营业
            shop = self.findOneByObjId(obj_id)
            if shop.types == '1' and data.get('checkStatus') == 'REFUSE':
                from apps.merchant.item.dao import ItemDao
                ItemDao().findAll().filter(shop__id=obj_id).update(status=0)
                shop.status = 0
                shop.save()
            
            # 调用父类的 update 方法
            return super().update(obj_id, data)
        except Exception as e:
            raise e

    def delete(self, obj_ids, data={}):
        try:
            if ShopDao().findAll().filter(id__in=obj_ids).filter(types='0').exists():
                raise VerifyException('有自营店不能删除')
            from apps.merchant.item.dao import ItemDao
            if ItemDao().findAll().filter(shop__id__in=obj_ids).exists():
                raise VerifyException('店铺下有商品不能删除，请先删除店铺下商品')
            return super().delete(obj_ids, data)
        except Exception as e:
            raise e